package com.fanqi.ipcapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.List;

//服务这边
public class TwoAppIpcActivity extends AppCompatActivity {

    private StringBuilder sb = new StringBuilder();

    private TextView bookListTv;
    private IBookManager manager;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            manager = (IBookManager) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two_app_ipc);
        bookListTv = findViewById(R.id.book_list);

        //服务这边也绑定这个服务，只要客户端那边调用了添加输入，这边也更新Ui
        Intent intent = new Intent(this, TwoAppIPCService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);

        IntentFilter filter = new IntentFilter();
        filter.addAction("com.fanqi.ipc.b");
        registerReceiver(receiver, filter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() != null) {
                if ("com.fanqi.ipc.b".equals(intent.getAction())) {
                    updateUi();
                }
            }
        }
    };

    private void updateUi() {
        List<Book> bookList = null;
        try {
            bookList = manager.getBooks();
            for (int i = 0; i < bookList.size(); i++) {
                sb.append(i + "书名：" + bookList.get(i).getName());
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        bookListTv.setText("");
        bookListTv.setText(sb.toString());

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
        unregisterReceiver(receiver);
    }
}
